class Store
  module Friendable
    extend ActiveSupport::Concern

    def friends
      Store.friends(self.friend_ids)
    end

    def agree(friend)
      self.transaction do
        (friend_ids << friend.id).uniq
        (friend.friend_ids << self.id).uniq
        self.save!
        friend.save!
        # FriendBroadcastJob.perform_later(friend.id)
      end
    end

    def friended?(friend)
      friend_ids.include?(friend.id)
    end

    def friend_request(params, friend)
      a = []
      result = $redis.get("store_friend:#{params[:friend_id]}")
      if result.present?
        result = eval(result)
        result.push(params)
      else
        a.push(params)
        result = a
      end
      $redis.set("store_friend:#{params[:friend_id]}", result.uniq)
      FriendBroadcastJob.perform_now(friend.id)
    end
  end

  def unfriend(friend)
    fid = friend.is_a?(Store) ? friend.id : friend
    self.transaction do
      self.friend_ids.delete(fid)
      friend.friend_ids.delete(self.id)
      self.save!
      friend.save!
    end
  end

end
